var areaTemplate = '<li class="menuItem buttonMenu"></li>';
var batteries = {};

/**
 * Go to batterie choice
 */
function displayBatteries() {
	hideContainers();
	$('.navigationArea .batterieChoiceNavButton').addClass('hidden');
	$('.navigationArea .exerciceChoiceNavButton').addClass('hidden');
	showContainer('batterieChoiceContainer');
}

/**
 * Fill batteries
 * @param idx
 * @param batterie
 */
function fillBatterie(idx, area) {
	var shortKey = $('.menu.batteries li').size() + 1;
	var areaDom = $(areaTemplate);
	areaDom.attr('id', 'area_' + idx);
	areaDom.addClass('shortKey' + shortKey).append($('<div class="shortKeyIcon"></div>')).append($('<a/>').html(area.nom).attr('href', '#').click(
		function(){
			selectBatteries(area.nom, area.params);
			return false;
		}
	));
	var currentRow = parseInt((shortKey - 1) / 3);
	if ($(".menu.batteries div.rowContainer")[currentRow] === undefined) {
		$(".menu.batteries").append($("<div/>").addClass("rowContainer"));
	}
	$($(".menu.batteries div.rowContainer")[currentRow]).append(areaDom);
}

function selectBatteries(name, options) {
	/* ¤ONLINE */
	$.ajax({
		type: 'GET',
		url: serverPath + '/batterie/list?' + options,
		success: function(data) {
			batteries = data.batteries;

			loadBatterieList(name);
		},
		error: function(data) {
			displayPopup('Désolé, il ne semble pas y avoir de batteries dans cette catégorie pour le moment.');
		},
		dataType: 'json'
	});
	/* ¤ONLINEEND */
	/* ¤OFFLINE
	batteries = listOfBatteries[options];
	loadBatterieList(name);
	¤OFFLINEEND */
};

function loadBatterieList(name) {
	$('.menu.exercices').html('');
	
	// fill exercices
	$.each(batteries, fillExercice);

	// manage navigation
	if ($('body').hasClass('batterieChoiceContainerDisplayed')) {
		$('.navigationArea .batterieChoiceNavButton').html(name);
		$('.navigationArea .batterieChoiceNavButton').removeClass('hidden');
	}
	$('.navigationArea .exerciceChoiceNavButton').addClass('hidden');

	if ($(".menu.exercices li").length == 1) {
		hasOnlyOneBatterie = true;
		$(".menu.exercices li").find("a").trigger("click");
	} else {
		hasOnlyOneBatterie = false;
		displayExercices();
	}
}
